<template>
  <div>
    <BasicModal
      v-bind="$attrs"
      v-model:visible="showContract"
      :title="getTitle()"
      @ok="onSubmit"
      :useWrapper="false"
    >
      <Form
        class="form_box"
        ref="formRef"
        :model="formState"
        :rules="rules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 14 }"
      >
        <FormItem label="招投标类型" name="types">
          <CheckboxGroup v-model:value="formState.types" placeholder="请选择招投标类型">
            <Checkbox value="10">建筑设计</Checkbox>
            <Checkbox value="11">城乡规划</Checkbox>
            <Checkbox value="12">景观项目</Checkbox>
            <Checkbox value="13">市政项目</Checkbox>
            <Checkbox value="14">勘察项目</Checkbox>
            <Checkbox value="15">施工项目</Checkbox>
          </CheckboxGroup>
        </FormItem>
        <FormItem label="资质公司编号" name="licenseCompanyId">
          <Select
            allowClear
            v-model:value="formState.licenseCompanyId"
            placeholder="请选择资质公司编号"
          >
            <SelectOption v-for="(item, index) in allLicense" :value="item.id" :key="index">{{
              item.name
            }}</SelectOption>
          </Select>
        </FormItem>
        <FormItem label="报名时间" name="signDate">
          <DatePicker
            :format="'YYYY-MM-DD'"
            valueFormat="YYYY-MM-DD"
            v-model:value="formState.signDate"
          />
        </FormItem>
        <FormItem label="开标时间" name="openDate">
          <DatePicker
            :format="'YYYY-MM-DD'"
            valueFormat="YYYY-MM-DD"
            v-model:value="formState.openDate"
          />
        </FormItem>
        <FormItem label="保证金" name="amount">
          <Input v-model:value="formState.amount" placeholder="请输入保证金" types="number" />
        </FormItem>
        <FormItem label="标书类型" name="documentType">
          <Select allowClear v-model:value="formState.documentType" placeholder="请选择标书类型">
            <SelectOption value="10">电子</SelectOption>
            <SelectOption value="11">纸质</SelectOption>
          </Select>
        </FormItem>
        <FormItem label="对接人电话" name="comment">
          <Input v-model:value="formState.comment" placeholder="请输入对接人电话" />
        </FormItem>
        <FormItem label="投标资料清单" name="urlFile">
          <Upload
            :multiple="true"
            :before-upload="beforeUpload"
            :file-list="formState.urlFile"
            @change="handleChange"
          >
            <a-button>
              <upload-outlined></upload-outlined>
              上传附件
            </a-button>
          </Upload>
        </FormItem>
        <FormItem label="支付凭证附件" name="voucherFile">
          <Upload
            :multiple="true"
            :before-upload="beforeUploadvoucher"
            :file-list="formState.voucherFile"
            @change="handleChangevoucher"
          >
            <a-button>
              <upload-outlined></upload-outlined>
              上传附件
            </a-button>
          </Upload>
        </FormItem>
      </Form>
    </BasicModal>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, onMounted, getCurrentInstance } from 'vue';
  import {
    Modal,
    Form,
    Input,
    FormItem,
    DatePicker,
    Upload,
    Select,
    SelectOption,
    Checkbox,
    CheckboxGroup,
  } from 'ant-design-vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { fileUploadApi, fileViewApi } from '/@/api/projectManagement';
  import { useRoute } from 'vue-router';
  import {
    addBiddingRecord,
    editBiddingRecord,
    addApplyBiddingRecord,
    editApplyBiddingRecord,
  } from '/@/api/api';
  import { BasicModal } from '/@/components/Modal';

  const instance = getCurrentInstance();
  let route = useRoute();

  const getTitle = () => {
    const baseText = isEdit.value ? '编辑' : '添加';
    const recordType = projectKind.value === 'partner' ? '申请招投标记录' : '招投标记录';
    return `${baseText}${recordType}`;
  };

  const { createMessage } = useMessage();

  const formRef = ref();
  const formState = reactive({
    projectId: '',
    types: [],
    licenseCompanyId: '',
    signDate: '',
    openDate: '',
    amount: '',
    documentType: '',
    comment: '',
    url: '',
    urlFile: [],
    voucher: '',
    voucherFile: [],
  });
  onMounted(() => {
    console.log(route.query, 'query');
  });
  let validatePass2 = () => {
    if (formState.urlFile.length <= 0) {
      return Promise.reject('请上传附件');
    } else {
      return Promise.resolve();
    }
  };
  let validatePass3 = () => {
    if (formState.voucherFile.length <= 0) {
      return Promise.reject('请上传附件');
    } else {
      return Promise.resolve();
    }
  };
  const rules = {
    types: [{ required: true, message: '请选择招投标类型' }],
    licenseCompanyId: [{ required: true, message: '请选择资质公司编号' }],
    signDate: [{ required: true, message: '请选择报名时间' }],
    openDate: [{ required: true, message: '请选择开标时间' }],
    amount: [{ required: true, message: '请输入保证金' }],
    documentType: [{ required: true, message: '请选择标书类型' }],
    comment: [{ required: true, message: '请输入对接人电话' }],
    urlFile: [{ required: true, validator: validatePass2, trigger: 'change' }],
    voucherFile: [{ required: true, validator: validatePass3, trigger: 'change' }],
  };

  const beforeUpload = (file) => {
    let formData = new FormData();
    formData.append('file', file);
    fileUploadApi(formData).then((res) => {
      formState.urlFile = [file];
      formState.url = res;
      formRef.value.clearValidate('urlFile');
    });

    return false;
  };
  const handleChange = (info) => {
    if (info.file.status == 'removed') {
      formState.urlFile = [];
    }
  };

  const beforeUploadvoucher = (file) => {
    let formData = new FormData();
    formData.append('file', file);
    fileUploadApi(formData).then((res) => {
      formState.voucherFile = [file];
      formState.voucher = res;
      formRef.value.clearValidate('voucherFile');
    });

    return false;
  };
  const handleChangevoucher = (info) => {
    if (info.file.status == 'removed') {
      formState.voucherFile = [];
    }
  };

  const showContract = ref(false);
  const allLicense = ref([]);
  const projectKind = ref();
  const kindName = ref();

  const init = (data) => {
    showContract.value = true;
    allLicense.value = data.allLicense;
    formState.projectId = data.projectId;
    // partner 为合伙人，公司项目不传
    projectKind.value = data.projectKind;
    if (data.isEdit == true) {
      isEdit.value = true;
      editData.value = data.editData;
      kindName.value = projectKind.value == 'partner' ? 'tenderApplyResponse' : 'tenderResponse';
      formState.licenseCompanyId = editData.value[kindName.value].licenseCompanyId;
      formState.signDate = editData.value[kindName.value].signDate;
      formState.types = editData.value[kindName.value].types;
      formState.comment = editData.value[kindName.value].comment;
      formState.amount = editData.value[kindName.value].amount;
      formState.openDate = editData.value[kindName.value].openDate;
      formState.documentType = editData.value[kindName.value].documentType;
      formState.url = editData.value[kindName.value].url;
      formState.voucher = editData.value[kindName.value].voucher;
      fileViewApi(formState.url).then((res) => {
        let nameExtension = formState.url.split('.')[1];
        let file = new File([res], `投标资料清单.${nameExtension}`, { types: nameExtension }); // 创建一个File对象
        file.uid = 'v-' + Date.now();
        formState.urlFile = [file];
        console.log(file, '图片');
      });
      if(formState.voucher){
        fileViewApi(formState.voucher).then((res) => {
          let nameExtension = formState.url.split('.')[1];
          let file = new File([res], `支付凭证附件.${nameExtension}`, { types: nameExtension }); // 创建一个File对象
          file.uid = 'v-' + Date.now();
          formState.voucherFile = [file];
          console.log(file, '图片');
        });
      }
    } else {
      isEdit.value = false;
      editData.value = {};
      resetForm();
    }
  };
  const isEdit = ref(false);
  const editData = ref({});
  const onSubmit = () => {
    console.log(formState);
    formRef.value
      .validate()
      .then(() => {
        if (isEdit.value == true) {
          const { urlFile,voucherFile, ...restFormState } = formState;
          if (projectKind.value == 'partner') {
            editApplyBiddingRecord({
              ...restFormState,
              id: editData.value[kindName.value].id,
            }).then((res) => {
              if (res != false) {
                createMessage.success('编辑成功');
                isEdit.value = false;
                editData.value = {};
                if (instance) {
                  instance.proxy?.$emit('tableNeedUpdate');
                }
                resetForm();
                showContract.value = false;
              }
            });
          } else {
            editBiddingRecord({
              ...restFormState,
              id: editData.value[kindName.value].id,
            }).then((res) => {
              if (res != false) {
                createMessage.success('编辑成功');
                isEdit.value = false;
                editData.value = {};
                if (instance) {
                  instance.proxy?.$emit('tableNeedUpdate');
                }
                resetForm();
                showContract.value = false;
              }
            });
          }
        } else {
          const { urlFile, ...restFormState } = formState;
          if (projectKind.value == 'partner') {
            addApplyBiddingRecord({
              ...restFormState,
            }).then((res) => {
              if (res != false) {
                createMessage.success('添加成功');
                if (instance) {
                  instance.proxy?.$emit('tableNeedUpdate');
                }
                resetForm();
                showContract.value = false;
              }
            });
          } else {
            addBiddingRecord({
              ...restFormState,
            }).then((res) => {
              if (res != false) {
                createMessage.success('添加成功');
                if (instance) {
                  instance.proxy?.$emit('tableNeedUpdate');
                }
                resetForm();
                showContract.value = false;
              }
            });
          }
        }
      })
      .catch((error: any) => {
        console.log('error', error);
      });
  };
  const resetForm = () => {
    formState.licenseCompanyId = '';
    formState.signDate = '';
    formState.types = [];
    formState.comment = '';
    formState.url = '';
    formState.urlFile = [];
    formState.openDate = '';
    formState.amount = '';
    formState.documentType = '';
  };

  defineExpose({
    init,
  });
</script>
<style>
  .scroll-container .scrollbar__wrap {
    margin-bottom: 0 !important;
  }
  .ant-checkbox-wrapper {
    margin-left: 0 !important;
  }
</style>
